<template>
  <div class="app-container">
    <!-- 产品资料维护 -->

    <el-row :gutter="24">
      <el-col :lg="24" :xs="24">
        <div class="search-bar">
          <!-- 搜索 -->
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="产品名称" prop="productName">
              <el-input
                v-noSpace
                v-model="queryParams.productName"
                placeholder="请输入产品名称"
                clearable
                class="!w-[192px]"
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="产品类别" prop="categoryCode">
              <el-select
                v-model="queryParams.categoryCode"
                placeholder="请选择产品类别"
                class="!w-[192px]"
                clearable
                filterable
                @keyup.enter="handleQuery"
                @visible-change="getProductType"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="类型" prop="productType">
              <el-select
                v-model="queryParams.productType"
                placeholder="请选择类型"
                class="!w-[192px]"
                clearable
                filterable
                @change="handleQuery"
                @visible-change="getType"
              >
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="标签" prop="packageType">
              <el-select
                v-model="selectedValue"
                placeholder="请选择标签"
                class="!w-[192px]"
                clearable
                multiple
                @change="handleChange"
                @visible-change="handleVisibleChange"
              >
                <!-- 自定义输入框 -->
                <el-option v-if="showCustomOption" :value="customValue" :label="customLabel">
                  <div style="" @click.stop>
                    <el-input
                      v-noSpace
                      v-model="customKey"
                      placeholder="请输入标签名"
                      maxlength="20"
                      style="width: 100px; margin-right: 5px"
                      @click.stop
                      @keyup.enter="addCustomOption"
                    />
                    <el-input
                      v-noSpace
                      v-model="customValue"
                      style="width: 100px"
                      placeholder="请输入标签值"
                      maxlength="50"
                      @click.stop
                      @keyup.enter="addCustomOption"
                    />
                  </div>
                </el-option>
                <el-option
                  v-for="(item, index) in optionsList"
                  :key="item.uniqueId"
                  :label="item.label"
                  :value="item.uniqueId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="包装方式" prop="packageType">
              <el-select
                v-model="queryParams.packageType"
                placeholder="请选择包装方式"
                class="!w-[192px]"
                @change="handleQuery"
                clearable
              >
                <el-option
                  v-for="item in packageTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
              <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
              <el-button
                type="warning"
                icon="plus"
                @click="handleEdit({}, 'add')"
                v-hasPerm="'sys:productInfo:edit'"
              >
                新增
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-card shadow="never">
          <el-table
            v-loading="loading"
            show-overflow-tooltip
            :tooltip-formatter="tableRowFormatter"
            :data="pageData"
            @row-click="handClikRow"
          >
            <el-table-column prop="productName" label="产品名称" align="center" />
            <el-table-column prop="productType" label="类型" align="center">
              <template #default="scope">
                {{ getStatusByCode(scope.row.productType) }}
              </template>
            </el-table-column>
            <el-table-column prop="categoryName" label="产品类别" align="center" />
            <el-table-column prop="unit" label="单位" align="center">
              <template #default="scope">
                {{ unitFormat(scope.row.unit) }}
              </template>
            </el-table-column>
            <el-table-column prop="packageType" label="包装方式" align="center" />
            <el-table-column prop="packageSize" label="规格（cm）" align="center">
              <!-- <template #default="scope">
                {{ `${scope.row.ctnL}` + `x` + `${scope.row.ctnW}` + `x` + `${scope.row.ctnH}` }}
              </template> -->
            </el-table-column>
            <!-- <el-table-column prop="basketCapacity" label="单框容量" width="150" align="center" /> -->
            <el-table-column prop="expireDay" label="保质期" align="center" />
            <el-table-column prop="labels" label="标签" align="center">
              <template #default="scope">
                <div style="display: flex">
                  <el-tag v-for="(item, index) in scope.row.labels" type="info">
                    {{ item.labelName + ":" + item.labelValue }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="上架" align="center">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.status"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleStatusChange(scope.row)"
                />
              </template>
            </el-table-column>

            <!-- <el-table-column prop="ctnGrossWeight" label="毛重" width="100" align="center" /> -->
            <!-- <el-table-column prop="ctnNetWeight" label="净重" width="100" align="center" /> -->
            <!-- <el-table-column prop="costPrice" label="成本单价" align="center" /> -->
            <!-- <el-table-column prop="salesPrice" label="销售单价" align="center" /> -->
            <!-- <el-table-column prop="minOrderQty" label="最少订购" width="150" align="center" /> -->
            <!-- <el-table-column prop="safetyQty" label="安全库存" width="150" align="center" /> -->
            <el-table-column prop="remark" label="备注" align="center" show-overflow-tooltip />
            <el-table-column label="操作" fixed="right" width="150" align="center">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="handleEdit(scope.row, 'edit')"
                  v-hasPerm="'sys:productInfo:edit'"
                >
                  编辑
                </el-button>
                <el-button type="primary" size="small" link @click="handleEdit(scope.row, 'info')">
                  查看
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  link
                  @click="handleDel(scope.row)"
                  v-hasPerm="'sys:productInfo:del'"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增/修改弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="1000px"
      class="df"
      @close="handleCloseDialog"
    >
      <el-form
        ref="dialogFormRef"
        :model="dialogParams"
        :inline="true"
        :disabled="dialog.type == 'info' ? true : false"
        label-width="150px"
        :rules="rules"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input
                v-noSpace
                v-model="dialogParams.productName"
                style="width: 200px"
                placeholder="请输入产品名称"
                clearable
                maxlength="100"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="产品类别" prop="categoryCode">
              <el-select
                v-model="dialogParams.categoryCode"
                placeholder="请选择产品类别"
                style="width: 200px"
                clearable
                filterable
                @visible-change="getProductType"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="productType">
              <el-select
                v-model="dialogParams.productType"
                placeholder="请选择类型"
                style="width: 200px"
                clearable
              >
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="包装方式" prop="packageType">
              <el-select
                v-model="dialogParams.packageType"
                placeholder="请选择产品类别"
                style="width: 200px"
                clearable
                filterable
                @visible-change="getProductType"
              >
                <el-option
                  v-for="item in packageTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="规格" prop="packageSize">
              <el-select
                v-model="dialogParams.packageSize"
                style="width: 200px"
                placeholder="请选择包装方式"
                clearable
              >
                <el-option
                  v-for="item in ctnLctnWctnHoptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保质期" prop="expireDay">
              <el-input
                v-noSpace
                v-model="dialogParams.expireDay"
                style="width: 200px"
                placeholder="请输入保质期"
              />
              <!-- <el-input v-noSpace
                v-model.number="dialogParams.expireDay"
                placeholder="请输入保质期"
                clearable
                style="width: 200px"
              /> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-select
                v-model="dialogParams.unit"
                placeholder="请选择单位"
                style="width: 200px"
                clearable
              >
                <el-option
                  v-for="item in unitOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单框容量" prop="basketCapacity">
              <el-input
                v-noSpace
                v-model="dialogParams.basketCapacity"
                placeholder="请输入单框容量"
                clearable
                style="width: 200px"
              />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="12">
            <el-form-item label="毛重" prop="ctnGrossWeight">
              <el-input v-noSpace
                v-model="dialogParams.ctnGrossWeight"
                placeholder="请输入毛重"
                clearable
                style="width: 200px"
              />
            </el-form-item>
          </el-col> -->

          <!-- <el-col :span="12">
            <el-form-item label="净重" prop="ctnNetWeight">
              <el-input v-noSpace
                v-model="dialogParams.ctnNetWeight"
                placeholder="请输入毛重"
                clearable
                style="width: 200px"
              />
            </el-form-item>
          </el-col> -->

          <!-- <el-col :span="12">
            <el-form-item label="成本单价" prop="costPrice">
              <el-input v-noSpace
                v-model="dialogParams.costPrice"
                placeholder="请输入成本单价"
                clearable
                style="width: 200px"
              />
            </el-form-item>
          </el-col> -->

          <el-col :span="12">
            <el-form-item label="销售单价" prop="salesPrice">
              <el-input
                v-noSpace
                v-model="dialogParams.salesPrice"
                placeholder="请输入销售单价"
                clearable
                style="width: 200px"
              />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="12">
            <el-form-item label="最少订购" prop="minOrderQty">
              <el-input v-noSpace
                v-model="dialogParams.minOrderQty"
                placeholder="请输入最少订购"
                clearable
                style="width: 200px"
              />
            </el-form-item>
          </el-col> -->

          <el-col :span="12">
            <el-form-item label="安全库存" prop="safetyQty">
              <el-input
                v-noSpace
                v-model="dialogParams.safetyQty"
                placeholder="请输入安全库存"
                clearable
                style="width: 200px"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="仓库类型" prop="warehouseCode">
              <el-select
                v-model="dialogParams.warehouseCode"
                placeholder="请选择仓库类型"
                style="width: 200px"
                clearable
                filterable
              >
                <el-option
                  v-for="item in wareOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="产品图片" prop="productImg">
              <MultiImageUpload
                v-model="productImgList"
                :data="uploadData"
                :disabled="dialog.type == 'info'"
              ></MultiImageUpload>
            </el-form-item>

            <!-- <el-upload
              v-model:file-list="productImgList"
              :action="uploadUrl"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="handleUploadSuccess"
              :data="uploadData"
              ref="uploadRef"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>

            <el-dialog v-model="imagePreviewVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog> -->
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-noSpace
                v-model="dialogParams.remark"
                placeholder="请输入备注"
                clearable
                type="textarea"
                :rows="4"
                style="width: 620px"
                maxlength="500"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="标签" prop="labels">
              <div style="display: flex; align-items: center; width: 620px">
                <el-input
                  v-noSpace
                  v-model="propertyData.labelName"
                  maxlength="20"
                  placeholder="请输入标签名"
                  clearable
                />
                <el-input
                  v-noSpace
                  v-model="propertyData.labelValue"
                  style="margin-left: 10px"
                  maxlength="50"
                  placeholder="请输入标签值"
                  clearable
                />
                <el-button
                  style="margin-left: 10px"
                  type="primary"
                  size="small"
                  @click="addproperty(propertyData)"
                >
                  添加标签
                </el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col v-if="propertyForm.length != 0" :span="24">
            <el-form-item label="标签列表" prop="labels">
              <el-card shadow="never" style="width: 620px">
                <el-table v-loading="loading" :data="propertyForm">
                  <el-table-column prop="labelName" label="标签名称" align="center">
                    <template #default="scope">
                      <el-input v-noSpace v-if="scope.row.edit" v-model="scope.row.labelName" />
                      <span v-else>{{ scope.row.labelName }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="labelValue" label="标签值" align="center">
                    <template #default="scope">
                      <el-input v-noSpace v-if="scope.row.edit" v-model="scope.row.labelValue" />
                      <span v-else>{{ scope.row.labelValue }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" fixed="right" width="100" align="center">
                    <template #default="scope">
                      <el-button
                        v-if="!scope.row.edit"
                        size="small"
                        link
                        type="primary"
                        @click="scope.row.edit = true"
                      >
                        编辑
                      </el-button>
                      <el-button
                        v-else
                        type="success"
                        size="small"
                        link
                        @click="scope.row.edit = false"
                      >
                        保存
                      </el-button>
                      <!-- <el-button
                        type="primary"
                        size="small"
                        link
                        @click="scope.row.edit=!scope.row.edit"
                      >
                        编辑
                      </el-button> -->
                      <el-button type="danger" size="small" link @click="propertyDel(scope.$index)">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer df">
          <el-button
            v-if="dialog.type == 'info' ? false : true"
            v-debounce="submitDialog"
            type="primary"
          >
            确 定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 子集新增/修改弹窗 -->
    <el-dialog
      v-model="rowDialog.visible"
      :title="rowDialog.title"
      width="900px"
      class="df"
      @close="handleCloserowDialog"
    >
      <el-form
        ref="rowDialogFormRef"
        :model="rowDialogParams"
        :inline="true"
        label-width="150px"
        :rules="rulesRow"
      >
        <el-row>
          <el-col :span="12">
            <!-- <el-form-item label="工序名称" prop="processName">
              <el-input v-noSpace v-model="rowDialogParams.processName" placeholder="请输入工序名称" clearable style="width: 200px" />
            </el-form-item> -->
            <el-form-item label="工序名称" prop="processName">
              <el-select
                v-model="rowDialogParams.processName"
                placeholder="请选择工序名称"
                style="width: 200px"
                clearable
                filterable
                @change="selectChange"
              >
                <el-option
                  v-for="item in procedureOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备" prop="eqptCode">
              <el-select
                v-model="rowDialogParams.eqptCode"
                placeholder="请选择设备"
                style="width: 200px"
                clearable
                filterable
                multiple
                disabled
              >
                <el-option
                  v-for="item in optionsProductName"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产能（天）" prop="capacity">
              <el-input-number
                v-model="rowDialogParams.capacity"
                placeholder="请输入产能（天）"
                clearable
                style="width: 200px"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-noSpace
            v-model="rowDialogParams.remark"
            placeholder="请输入备注"
            clearable
            type="textarea"
            :rows="4"
            style="width: 620px"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer df">
          <el-button type="primary" @click="submitRowDialog">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-card shadow="never" class="mt-2">
      <div class="df-sb">
        <p>以下列表顺序可以拖动</p>
        <el-button
          v-if="rowId"
          type="warning"
          icon="plus"
          @click="handleRowEdit({}, 'add')"
          v-hasPerm="'sys:productInfo:process:edit'"
        >
          新增
        </el-button>
      </div>
      <div class="draggable">
        <el-table :data="rowData" row-key="id">
          <el-table-column prop="processName" label="工序名称" width="150" align="center" />
          <el-table-column prop="sortSeq" label="生产顺序" align="center" />
          <!-- <el-table-column prop="prodTime" label="生产时长" /> -->
          <el-table-column prop="capacity" label="产能（天）" align="center" />
          <el-table-column prop="remark" label="备注" align="center" />
          <el-table-column prop="createName" label="创建人" align="center" />
          <el-table-column prop="createTime" label="创建时间" align="center" />
          <el-table-column label="操作" fixed="right" width="250" align="center">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                link
                @click="handleRowEdit(scope.row, 'edit')"
                v-hasPerm="'sys:productInfo:process:edit'"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                link
                @click="handleRowDel(scope.row)"
                v-hasPerm="'sys:productInfo:process:del'"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import productInfoAPI, {
  productInfoPageQuery,
  productInfoPageVO,
  productInfoRowPageVO,
  productFormDialog,
} from "@/api/productInfo/productInfo";
import configApi, { ConfigType } from "@/api/config/config";
import { FormItemRule } from "element-plus/es";
import { tableRowFormatter, validatePositiveInteger } from "@/utils/index";
import Sortable from "sortablejs";
import basicProcessAPI from "@/api/basicProcess/basicProcess";
import { Plus } from "@element-plus/icons-vue";
import type { UploadFile, UploadFiles, UploadProps, UploadUserFile } from "element-plus";

import { getToken } from "@/utils/auth";
import FileAPI from "@/api/file";

defineOptions({
  name: "User",
  inheritAttrs: false,
});

const optionsProductName = ref<{ value: string; label: string }[]>([]); // 显式指定类型
// 默认选项
interface OptionItem {
  labelName: string;
  labelValue: string;
  label: string;
  uniqueId: string; // 唯一标识符
}
const optionsList = ref<OptionItem[]>([]);
const selectedValue = ref<string[]>([]);
// 自定义键值对
const customKey = ref("");
const customValue = ref("");
// 是否显示自定义输入框
const showCustomOption = ref(false);
// 自定义选项的标签
const customLabel = computed(() => {
  return customKey.value ? `${customKey.value}: ${customValue.value}` : "自定义";
});
// 生成唯一标识符
const generateUniqueId = (label: string, value: string) => {
  return `${label}-${value}-${Math.random().toString(36).substring(2, 9)}`;
};
// 添加自定义选项
const addCustomOption = () => {
  if (customKey.value && customValue.value) {
    // 将自定义键值对添加到选项列表中
    const uniqueId = generateUniqueId(customKey.value, customValue.value);
    optionsList.value.push({
      labelValue: customValue.value,
      labelName: customKey.value,
      label: customLabel.value,
      uniqueId,
    });

    // 选中自定义选项
    selectedValue.value.push(uniqueId);
    // 将自定义值添加到选中的值中
    // queryParams.labels.push(customValue.value);
    // 清空输入框
    customKey.value = "";
    customValue.value = "";
    // showCustomOption.value = false;
    // 手动收起下拉框
    // if (selectRef.value) {
    //   selectRef.value.blur();
    // }
  }
};
// 处理选择事件
const handleChange = (value: any) => {
  if (value === customValue.value) {
    addCustomOption();
  }
};
// 当下拉框显示/隐藏时触发
const handleVisibleChange = (visible: any) => {
  showCustomOption.value = visible;
  if (!visible && customKey.value && customValue.value) {
    addCustomOption();
  }
};

// 属性添加form表
interface PropertyForm {
  labelName?: string;
  labelValue?: string;
  edit?: boolean;
  id?: string;
}
const propertyData: PropertyForm = reactive({});
const propertyForm: PropertyForm[] = reactive([]);
// 属性列表添加
const addproperty = (row: any) => {
  console.log(row);
  row.edit = false;
  // Object.assign(propertyForm, { ...row });
  propertyForm.push(JSON.parse(JSON.stringify(row)));
  propertyData.labelValue = "";
  propertyData.labelName = "";
  console.log(propertyForm, "propertyForm");
};
// 属性列表删除
const propertyDel = (index: number) => {
  console.log(index);
  propertyForm.splice(index, 1);
};

const queryFormRef = ref(ElForm);

const queryParams = reactive<productInfoPageQuery>({
  pageNum: 1,
  pageSize: 10,
  productType: 1,
});

const pageData = ref<productInfoPageVO[]>();
const rowData = ref<productInfoRowPageVO[]>();
const total = ref(0);
const listTotal = ref(0);
const loading = ref(false);

// 新增/修改弹窗
const dialog = reactive({
  visible: false,
  title: "",
  type: "",
});

const rowDialog = reactive({
  visible: false,
  title: "",
  type: "",
});
const dialogFormRef = ref(ElForm);
const rowDialogFormRef = ref(ElForm);

const rowId = ref<number>();
const rowObj = ref();

const dialogParams: productFormDialog = reactive({});

const rowDialogParams = reactive({
  processName: "",
  prodTime: 0,
  capacity: 0,
  ctnGrossWeight: 0,
  remark: "",
  parentCode: 0,
  processCode: 0,
  eqptCode: [],
});

//上传图片

//上传路径
const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + "/core/api/file/upload");
const uploadRef = ref();
const uploadData = ref({
  bizType: "public",
  token: getToken(),
});

const productImgList = ref<{ name: string; url: string }[]>([]);

const dialogImageUrl = ref("");

const options = ref<{ value: string; label: string }[]>([]); // 显式指定类型

const packageTypeOptions = ref<{ value: string; label: string }[]>([]); // 显式指定类型
const unitOptions = ref<{ value: string; label: string }[]>([]); // 显式指定类型
const unitFormat = (value: any) => {
  return unitOptions.value.find((item: any) => item.value === value)?.label;
  // return unitOptions.value.find((item:any)=>item.codeValue===codeValue).codeName
};

const ctnLctnWctnHoptions = ref<{ value: string; label: string }[]>([]); // 显式指定类型

const typeOptions = ref<{ value: number; label: string }[]>([]); // 显式指定类型

const wareOptions = ref<{ value: string; label: string }[]>([]); // 显式指定类型

const procedureOption = ref<{ value: string; label: string }[]>([]); // 显式指定类型

const rules = reactive<Record<string, FormItemRule[]>>({
  productName: [{ required: true, message: "请输入产品名称", trigger: "blur" }],
  categoryCode: [{ required: true, message: "请选择产品类别", trigger: "change" }],
  packageType: [{ required: true, message: "请选择包装方式", trigger: "change" }],
  productType: [{ required: true, message: "请选择类型", trigger: "change" }],
  warehouseCode: [{ required: true, message: "请选择仓库类型", trigger: "change" }],
  ctnLctnWctnH: [{ required: true, message: "请选择规格", trigger: "change" }],
  // basketCapacity: [
  //   { required: true, message: "单框容量是必填项", trigger: "blur" },
  //   { type: "number", message: "单框容量必须是一个数字", trigger: "blur" },
  //   { min: 0, type: "number", message: "单框容量必须大于等于0", trigger: "blur" },
  // ],
  expireDay: [{ required: true, validator: validatePositiveInteger, trigger: "blur" }],
  ctnGrossWeight: [{ required: true, validator: validatePositiveInteger, trigger: "blur" }],
  ctnNetWeight: [{ required: true, validator: validatePositiveInteger, trigger: "blur" }],
  costPrice: [{ required: true, validator: validatePositiveInteger, trigger: "blur" }],
  salesPrice: [{ required: true, validator: validatePositiveInteger, trigger: "blur" }],
  minOrderQty: [{ required: true, validator: validatePositiveInteger, trigger: "blur" }],
  safetyQty: [{ required: true, validator: validatePositiveInteger, trigger: "blur" }],
});

const rulesRow = reactive<Record<string, FormItemRule[]>>({
  processName: [{ required: true, message: "请输入工序名称", trigger: "blur" }],
  prodTime: [
    { required: true, message: "生产时长是必填项", trigger: "blur" },
    { type: "number", message: "生产时长必须是一个数字", trigger: "blur" },
    { min: 0, type: "number", message: "生产时长必须大于等于0", trigger: "blur" },
  ],
  // eqptCode: [
  //   {
  //     required: true,
  //     message: "请选择设备",
  //     trigger: "change",
  //   },
  //   { type: "array", min: 1, message: "至少选择一个设备" },
  // ],
  capacity: [
    { required: true, message: "产能是必填项", trigger: "blur" },
    { type: "number", message: "产能必须是一个数字", trigger: "blur" },
    { min: 0, type: "number", message: "产能必须大于等于0", trigger: "blur" },
  ],
  ctnGrossWeight: [
    { required: true, message: "毛重是必填项", trigger: "blur" },
    { type: "number", message: "毛重必须是一个数字", trigger: "blur" },
    { min: 0, type: "number", message: "毛重必须大于等于0", trigger: "blur" },
  ],
});
//产品列表 potato carrot beef
const productList = ref<
  {
    codeName: string;
    codeValue: string;
  }[]
>([]);
//规格
const getctnLctnWctnH = () => {
  configApi.getConfigListByType("packageSize" as ConfigType).then((res) => {
    ctnLctnWctnHoptions.value = res.map((item: any) => {
      return {
        value: item.codeValue,
        label: item.codeName,
      };
    });
  });
};

//获取设备列表
const getDeviceList = () => {
  basicProcessAPI.getDeviceList({ pageNum: 1, pageSize: 999 }).then((res) => {
    console.log(res, "设备列表");

    optionsProductName.value = res.list.map((item: any) => ({
      value: item.code,
      label: item.name,
    }));
  });
};
//根据工序获取设备列表
const getDeviceListByProcess = (bindProcess: string) => {
  productInfoAPI.getProcedure({ pageNum: 1, pageSize: 999, code: bindProcess }).then((res: any) => {
    console.log(res.list[0], "设备列表");
    rowDialogParams.eqptCode = res.list[0].eqptCode.split(",");
  });
};

const getType = () => {
  configApi.getConfigListByType("productType" as ConfigType).then((res) => {
    typeOptions.value = res.map((item: any) => {
      return {
        value: Number(item.codeValue),
        label: item.codeName,
      };
    });
  });
};

const getWare = () => {
  configApi.getConfigListByType("warehouseCode" as ConfigType).then((res) => {
    wareOptions.value = res.map((item: any) => {
      return {
        value: item.codeValue,
        label: item.codeName,
      };
    });
  });
};
//packageType包装方式
const getpackageType = () => {
  configApi.getConfigListByType("packageType" as ConfigType).then((res) => {
    packageTypeOptions.value = res.map((item: any) => {
      return {
        value: item.codeValue,
        label: item.codeName,
      };
    });
  });
};
//单位
const getUnitType = () => {
  configApi.getConfigListByType("unit" as ConfigType).then((res) => {
    unitOptions.value = res.map((item: any) => {
      return {
        value: item.codeValue,
        label: item.codeName,
      };
    });
  });
};

const getProductType = () => {
  productInfoAPI
    .getTypePage({ pageNum: 1, pageSize: 20 })
    .then((data) => {
      options.value = (data?.list || []).map((item: any) => ({
        value: item.code,
        label: item.name,
      }));
    })
    .finally(() => {
      loading.value = false;
    });
};

//工序列表

const getProcedureList = () => {
  productInfoAPI
    .getProcedure({ pageNum: 1, pageSize: 20 })
    .then((data) => {
      procedureOption.value = (data?.list || []).map((item: any) => ({
        value: item.code,
        label: item.name,
        remark: item.remark,
        capacity: item.capacity,
        personPlan: item.personPlan,
      }));
    })
    .finally(() => {
      loading.value = false;
    });
};

// 查询
function handleQuery() {
  if (selectedValue.value.length > 0) {
    let labels = selectedValue.value.map((item) =>
      optionsList.value.find((items) => items.uniqueId === item)
    );
    console.log();
    queryParams.labels = JSON.parse(JSON.stringify(labels));
  }
  // loading.value = true;
  console.log(queryParams, "queryParams");
  productInfoAPI
    .getPage(queryParams)
    .then((data) => {
      pageData.value = [...(data?.list as any)];
      total.value = data.total;
      rowData.value = [];
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  selectedValue.value = [];
  console.log(queryParams);
  // 使用 Object.assign 修改 queryParams 的属性
  // Object.assign(queryParams, {
  //   pageNum: 1,
  //   pageSize: 10,
  //   productName: undefined,
  //   productType: "1",
  // });
  // queryParams.deptId = undefined;
  // queryParams.createTime = undefined;
  handleQuery();
}

//产品上下架
const handleStatusChange = async (row: any) => {
  try {
    ElMessageBox.confirm("确定要更新状态吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        // 更新状态API调用成功后的处理逻辑
        productInfoAPI.submitDialog({ id: row.id, status: row.status }).then((res) => {
          console.log(res);
          ElMessage.success("状态更新成功");
          handleQuery();
        });
      })
      .catch(() => {
        handleQuery();
      });

    // TODO: 调用更新状态API
  } catch (error) {
    console.error("状态更新失败:", error);
  }
};

function handleEdit(row: any, type: any) {
  console.log(row, "row");
  dialog.type = type;
  dialog.visible = true;
  let upData = {};

  if (type == "edit") {
    dialog.title = "编辑";
    upData = { ...row };
    nextTick(() => {
      Object.assign(dialogParams, { ...upData });
      Object.assign(propertyForm, { ...row.labels });

      productImgList.value = JSON.parse(dialogParams.productImg || "");
      console.log(JSON.parse(dialogParams.productImg || ""), "productImgList");
    });

    // dialogParams.ctnLctnWctnH = row.packageSize;
    // dialogParams.productType = String(row?.productType);
  } else if (type == "add") {
    dialog.title = "新增";
    delete dialogParams.id;
    delete dialogParams.code;
  } else {
    dialog.title = "查看";
    upData = { ...row };
    nextTick(() => {
      Object.assign(dialogParams, { ...upData });
      Object.assign(propertyForm, { ...row.labels });
      productImgList.value = JSON.parse(dialogParams.productImg || "");
    });
  }
}

function handleDel(row: any) {
  ElMessageBox.confirm("确定要删除该数据吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      productInfoAPI
        .delDialog({ id: row.id })
        .then((data) => {
          ElMessage.success("操作成功");
          handleQuery();
        })
        .catch((err) => {
          // ElMessage.error(`${err}`);
        })
        .finally(() => {
          loading.value = false;
        });
    })
    .catch(() => {
      // 取消删除
    });
}

function handleCloseDialog() {
  dialogFormRef.value?.clearValidate();
  dialogFormRef.value?.resetFields();
  propertyForm.length = 0;
  console.log(dialogParams, "dialogParams");
  dialogImageUrl.value = "";
  productImgList.value = [];
  dialog.visible = false;
}

function handleCloserowDialog() {
  rowDialogFormRef.value?.clearValidate();
  rowDialogFormRef.value?.resetFields();
  rowDialog.visible = false;
}

function clearRowDialogFormData() {
  let data = {
    processName: "",
    prodTime: 0,
    capacity: 0,
    ctnGrossWeight: 0,
    remark: "",
    id: "",
  };
  Object.assign(rowDialogParams, { ...data });
}

// 提交弹窗
function submitDialog() {
  // ctnLctnWctnH
  propertyForm.map((item) => delete item.edit);
  dialogFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    let filterFile = [];
    productImgList.value.forEach((item) => {
      filterFile.push({
        name: item.name,
        url: item.url,
      });
    });

    dialogParams.productImg = JSON.stringify(productImgList.value);
    console.log(dialogParams.productImg, "filterFile");

    let paramsData = <any>{};
    paramsData = { ...dialogParams };
    paramsData.labels = propertyForm;
    if (paramsData.packageSize) {
      paramsData.ctnLctnWctnH = paramsData.packageSize;
      const dimensions = paramsData.packageSize.split("×");
      paramsData.ctnL = Number(dimensions[0]);
      paramsData.ctnW = Number(dimensions[1]);
      paramsData.ctnH = Number(dimensions[2]);
    }
    productInfoAPI
      .submitDialog(paramsData)
      .then((data) => {
        ElMessage.success("操作成功");
        dialog.visible = false;
        handleQuery();
      })
      .catch((err) => {
        // ElMessage.error(`${err}`);
      })
      .finally(() => {
        loading.value = false;
      });
  });
}

// 提交弹窗
function submitRowDialog() {
  rowDialogFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    rowDialogParams.parentCode = rowObj?.value?.code;
    productInfoAPI
      .submitRowDialog(rowDialogParams)
      .then((data) => {
        ElMessage.success("操作成功");
        rowDialog.visible = false;
        handClikRow({ ...rowObj.value });
        clearRowDialogFormData();
      })
      .catch((err) => {
        // ElMessage.error(`${err}`);
      })
      .finally(() => {});
  });
}
function handClikRow(row: any) {
  rowId.value = row?.id;
  rowObj.value = { ...row };
  productInfoAPI
    .getRowList(row?.id)
    .then((data) => {
      rowData.value = [...(data as any)];
    })
    .catch((err) => {
      // ElMessage.error(`${err}`);
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleRowEdit(row: any, type: any) {
  rowDialog.type = type;
  if (type == "edit") {
    getDeviceListByProcess(row.processCode);
    rowDialog.title = "编辑";
    Object.assign(rowDialogParams, { ...row });
  } else {
    rowDialog.title = "新增";
    clearRowDialogFormData();
  }
  rowDialog.visible = true;
  getProcedureList();
}
function handleRowDel(row: any) {
  ElMessageBox.confirm("确定要删除该数据吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      productInfoAPI
        .delrowDialog({ id: row.id })
        .then((data) => {
          ElMessage.success("操作成功");
          handClikRow({ ...rowObj.value });
        })
        .catch((err) => {
          // ElMessage.error(`${err}`);
        })
        .finally(() => {
          loading.value = false;
        });
    })
    .catch(() => {
      // 取消删除
    });
}
function selectChange(value: any) {
  rowDialogParams.processName = value.label;
  rowDialogParams.processCode = value.value;
  rowDialogParams.capacity = value.capacity;
  getDeviceListByProcess(value.value);
}

// 在拖拽结束处理中添加检查
const rowDrop = () => {
  const tbody = document.querySelector(".draggable .el-table__body-wrapper tbody");
  if (!tbody) return;

  Sortable.create(tbody as HTMLElement, {
    draggable: ".draggable .el-table__row",
    onEnd({ newIndex, oldIndex }) {
      console.log(newIndex, "newIndex", oldIndex, "oldIndex");
      if (rowData.value && newIndex !== undefined && oldIndex !== undefined) {
        const currRow = rowData.value?.splice(oldIndex, 1)[0];
        if (currRow) {
          rowData.value?.splice(newIndex, 0, currRow);

          // 更新 sortSeq 为新的顺序值
          currRow.sortSeq = newIndex + 1; // 假设 sortSeq 从 1 开始

          // 更新排序序列并调用API
          productInfoAPI
            .drag({ id: currRow.id, sortSeq: currRow.sortSeq })
            .then((data) => {
              ElMessage.success("操作成功");
              handClikRow({ ...rowObj.value });
            })
            .catch((err) => {
              // ElMessage.error(`${err}`);
              // 回滚到原始位置
              // rowData.value?.splice(newIndex, 1);
              // rowData.value?.splice(oldIndex, 0, currRow);
            })
            .finally(() => {
              loading.value = false;
            });
        }
      } else {
        console.warn("rowData.value is undefined or indices are invalid");
      }
    },
  });
};

const getStatusByCode = (code: string) => {
  // 将 code 转换为 number 类型进行比较
  return typeOptions.value.find((item: any) => item.value == code)?.label;
};

onMounted(() => {
  // queryParams.productType = "1";
  handleQuery();
  getctnLctnWctnH();
  getProductType();
  getpackageType();
  getUnitType();
  getType();
  rowDrop();
  getWare();
  getDeviceList();
  getProcedureList();
});
</script>

<style lang="scss" scoped>
@use "@/styles/css/public" as *;

:deep(.el-input-number) {
  .el-input__inner {
    text-align: left;
  }
}

:deep(.el-input-number.is-without-controls .el-input__wrapper) {
  padding: 1px 11px;
}
</style>
